﻿using RazorEngine;
using RazorEngine.Templating;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LightWadf.Result
{
    public class RazorResult
    {
        private string htmlString = null;
        public string HtmlString
        {
            get
            {
                return this.htmlString;
            }
        }

        public RazorResult(string filePath) : this(filePath, null)
        {
        }

        public RazorResult(string filePath, Dictionary<string, object> model)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new TypeInitializationException("LightWadf.Result.RazorResult", new Exception("RazorResult 的初始化参数 filePath 为空"));
            }
            else
            {
                string[] paths = filePath.Split('/', '\\');
                string htmlPath = AppDomain.CurrentDomain.BaseDirectory;
                foreach (string path in paths)
                {
                    if (!string.IsNullOrEmpty(path))
                    {
                        htmlPath = Path.Combine(htmlPath, path);
                    }
                }
                if (File.Exists(htmlPath))
                {
                    this.htmlString = Engine.Razor.RunCompile(File.ReadAllText(htmlPath), "templateKey", null, model);
                }
                else
                {
                    throw new TypeInitializationException("LightWadf.Result.HtmlResult", new Exception("文件不存在 HtmlResult 初始化失败"));
                }
            }
        }
    }
}
